package com.android.djlmapp.activity.home.web;

import android.content.Intent;
import android.text.TextUtils;
import android.webkit.WebView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.web.base.BaseWebActivity;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.js_interface.BaseJsInterface;
import com.android.djlmapp.js_interface.buka.AbBukaJsInterfaceCallBack;
import com.android.djlmapp.js_interface.buka.BukaJsInterface;
import com.android.djlmapp.listener.read.SubReadDataListener;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.kaika.SubReadCardDataUtils;
import com.android.djlmapp.tools.read.WriteCardUtils;
import com.android.readcard.activity.ReadCardActivity;
import com.android.readcard.activity.WriteCardActivity;
import com.android.readcard.bean.BackReadInfo;
import com.android.readcard.bean.CardData;
import com.android.readcard.bean.ReadCardInfo;
import com.android.readcard.bean.ReadIccidAndWriteCardInfo;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.google.gson.Gson;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import static com.android.djlmapp.js_interface.BaseJsInterface.MORE_FUN_JS_SIGN_KEY;

/**
 * @Author wangziheng
 * @ProjectName djlm
 * @ClassName BukaActivity
 * @package com.android.djlmapp.activity.home.web
 * @data 2019/1/11 13:11
 * @Describe
 * @Change
 */
public class BukaActivity extends BaseWebActivity {

    private static final String TAG = "BukaActivity";
    /**
     * 补卡号码
     */
    private String mOrderNum;

    @Override
    public WebView getScrollView() {
        return new WebView(this);
    }

    @Override
    public String getJsInterfaceKey() {
        return MORE_FUN_JS_SIGN_KEY;
    }

    @Override
    public BaseJsInterface getJsInterface() {
        return new BukaJsInterface(this, mBkJsInterface,mAgentWeb);
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case EventCodes.EventReadCardCode.A:
                // 读卡
                BackReadInfo data = (BackReadInfo) event.getData();
                ReadCardInfo readInfo = data.getInfo();
                CardData cardData = data.getCardData();
                String chuanma = data.getChuanma();
                // 上传身份信息获取经办人数据
                SubReadCardDataUtils.getJingBanRenData(readInfo, cardData, chuanma, new SubReadDataListener() {
                    @Override
                    public void subPhotoSuc(String needJb, String photoUrl) {
                        Gson gson = new Gson();
                        String strJson = gson.toJson(cardData);
                        mAgentWeb.getJsAccessEntrace().quickCallJs("returnCARD", strJson);
                    }

                    @Override
                    public void subErr(String msg) {
                        ToastUtils.showShortToast(BukaActivity.this, msg);
                    }
                });
                break;
            case EventCodes.EventReadCardCode.B:
                // 返回iccid
                String mUrl = "";
                ReadIccidAndWriteCardInfo iccidData = (ReadIccidAndWriteCardInfo) event.getData();
                String iccidNum = iccidData.getIccidNum();
                int writeType = iccidData.getWriteType();
                String errMsg = iccidData.getErrMsg();
                // 错误信息
                String imsi = iccidData.getImsi();
                // imsi
                switch (writeType) {
                    case 1:
                        // 写卡
                        mUrl = GlobalUrls.BAI_KA;
                        // 上传iccid获取短信中心号和imsi并eventbus返回给WriteCardActivity
                        WriteCardUtils.startWrite(BukaActivity.this, mUrl, iccidNum, mOrderNum, "写卡");
                        break;
                    case 2:
                        // 补卡
                        mUrl = GlobalUrls.BU_KA;
                        // 上传iccid获取短信中心号和imsi并eventbus返回给WriteCardActivity
                        WriteCardUtils.startWrite(BukaActivity.this, mUrl, iccidNum, mOrderNum, "补卡");
                        break;
                    default:
                        break;
                }
                break;
            case EventCodes.EventReadCardCode.D:
                // 返回写卡结果
                String sucUrl = "";
                ReadIccidAndWriteCardInfo xiekaData = (ReadIccidAndWriteCardInfo) event.getData();
                String iccidNum1 = xiekaData.getIccidNum();
                int writeType1 = xiekaData.getWriteType();
                String errMsg1 = xiekaData.getErrMsg();
                // 错误信息
                String imsi1 = xiekaData.getImsi();
                // imsi
                // 判断errMsg是不是空,是空值就是写卡成功
                if (TextUtils.isEmpty(errMsg1)) {

                    // TODO 是否需要刷新web
                    switch (writeType1) {
                        case 1:
                            sucUrl = GlobalUrls.BAI_KA_OK;
                            WriteCardUtils.writeSucSubmit(BukaActivity.this, sucUrl, iccidNum1, mOrderNum, "写卡",null);
                            break;
                        case 2:
                            sucUrl = GlobalUrls.BU_KA_OK;
                             WriteCardUtils.writeSucSubmit(BukaActivity.this, sucUrl, iccidNum1, mOrderNum, "补卡",null);
                            break;
                        default:
                            break;
                    }

                } else {
                    // 写卡失败,提示错误
                    Event<String> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.E);
                    EventBusUtil.sendEvent(clearCardEvent);
                    switch (writeType1) {
                        case 1:
                            WriteCardUtils.showMsg(BukaActivity.this, "写卡结果", errMsg1);
                            break;
                        case 2:
                            WriteCardUtils.showMsg(BukaActivity.this, "补卡结果", errMsg1);
                            break;
                        default:
                            break;
                    }
                }
                break;
            default:
                break;
        }
    }

    private AbBukaJsInterfaceCallBack mBkJsInterface = new AbBukaJsInterfaceCallBack() {

        /**
         * 扫描身份证
         */
        @Override
        public void readIDCard() {
            startActivity(new Intent(BukaActivity.this, ReadCardActivity.class));
        }

        /**
         * 拍照 上传照片
         */
        @Override
        public void upImg() {
            takePhoto();
        }

        /**
         * 相册 选择照片上传/没有用到
         */
        @Override
        public void upImgs() {
            choosePhoto();
        }

        /**
         * 补卡回调
         * @param json
         */
        @Override
        public void bkSubmit(String json) {
            try {
                JSONObject jsonObject = new JSONObject(json);
                mOrderNum = jsonObject.optString("order_sn");
                if ("7".equals(jsonObject.optString("type"))) {
                    // 开始补卡
                    runOnUiThread(() -> readIccidOrWriteCard(2));
                }
            } catch (JSONException e) {
                ToastUtils.showShortToast(BukaActivity.this, "数据解析异常");
                e.printStackTrace();
            }
        }
    };

    private void readIccidOrWriteCard(final int mType) {
        // 蓝牙对话框
        startActivity(new Intent(BukaActivity.this, WriteCardActivity.class).putExtra("WriteType", mType));
    }

    @Override
    public void takeSuccess(TResult result) {
        ArrayList<TImage> images = result.getImages();
        String compressPath = images.get(0).getCompressPath();
        if (compressPath != null && !TextUtils.isEmpty(compressPath)) {
            File file = new File(compressPath);
            MyApplication.getInstance().getHttpTools().upLoadImg(file, new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    mAgentWeb.getJsAccessEntrace().quickCallJs("returnIMG", response.body());
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    showToast(getString(R.string.connect_sever_error_msg));
                }
            });
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        runOnUiThread(() -> showToast("压缩失败：" + msg));
    }
}
